Is it possible to store jQuery in a PHP variable and echo it?

I tried to do this and it isn't working. Either because it is impossible or I am doing it wrong. I have

      
function cancel_party_booking($link) {
	
	if(isset($_POST['cancel_booking'])){
	
	$party_id = $_GET['party_id'];
	$party_status = "Not Confirmed";
	
	$stmt = $link->prepare("UPDATE `party_form` SET `party_status` = ? WHERE `party_id` =  ? LIMIT 1");
	$stmt->bind_param("si", $party_status, $party_id);
	$stmt->execute();
	$stmt->close();
	$link->close();
	$sweetalert = "<script>
	swal({
		title: 'Error!'
		, text: 'Do you want to continue'
		, type: 'error'
		, confirmButtonText: 'Cool'
	})
</script>";	
		echo $sweetalert;
	}
}

Open in new window


https://limonte.github.io/sweetalert2/
LVL 1
Black SulfurAsked:
Who is Participating?
 
Dave BaldwinFixer of ProblemsCommented:
When a page is loaded into your browser, the browser goes thru everything on the page and puts it in the DOM (Document Object Model).  It then displays everything from the DOM... Not from the source code.  If your javascript is not part of the original page, then it does not get loaded in the DOM and does not run.  There may be a way to add it to the DOM after the page is loaded but I don't know what it is.

Now I use this line in several pages to load a javascript that is generated by PHP.
<script type="text/javascript" src="ip.php"></script>

Open in new window


It loads the javascript from this file.
<?php 
//"ip.php" example- display user IP address on any page
Header("content-type: application/x-javascript");
$remoteIP=$_SERVER['REMOTE_ADDR'];
echo "document.write(\"<div><b>Your IP address is: " . $remoteIP . "</b></div>\")";
?>

Open in new window

But it is loaded as part of the original page, not afterwards.
0
 
Dave BaldwinFixer of ProblemsCommented:
In order to work properly, the javascript or jquery must be on the page when it is first loaded.  That's when it gets put in the browser DOM to be interpreted.  If you try to simply post it after that, it just shows up as text.

In addition, if you are loading this as a separate file, you need the appropriate header sent first.
Header("content-type: application/x-javascript");

Open in new window

0
 
Black SulfurAuthor Commented:
Hi Dave, thanks for the response. Sorry, you have lost me a bit when you said:

In order to work properly, the javascript or jquery must be on the page when it is first loaded.

Are you referring to the page I am calling the function on? And if so, how do I do that?
0
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
Black SulfurAuthor Commented:
Hmm. This is complicated (for my tiny brain, lol).

So, I added the header part to my function:

function cancel_party_booking($link) {
	
	if(isset($_POST['cancel_booking'])){
	
	$party_id = $_GET['party_id'];
	$party_status = "Not Confirmed";
	
	$stmt = $link->prepare("UPDATE `party_form` SET `party_status` = ? WHERE `party_id` =  ? LIMIT 1");
	$stmt->bind_param("si", $party_status, $party_id);
	$stmt->execute();
	$stmt->close();
	$link->close();
	header("content-type: application/x-javascript");
	$sweetalert = "<script>
	swal({
		title: 'Error!'
		, text: 'Do you want to continue'
		, type: 'error'
		, confirmButtonText: 'Cool'
	})
</script>";	
		echo $sweetalert;
	}
}	

Open in new window


And then on my page that calls the function I have :

<script type="text/javascript" src="../functions.php"></script>

Open in new window


The page loads as normal but when I click on the button it then shows me all the code like I clicked on "view source" or something like that. I think you did mention that it might happen should I not do something correctly.
0
 
Black SulfurAuthor Commented:
I tried to simplify it. I just used simple javascript and didn't call the php page via script tags and it works. But it isn't what I want to achieve as I want to use Sweet Alert. Anyway, just thought I would show it.

function cancel_party_booking($link) {
	
	if(isset($_POST['cancel_booking'])){
	
	$party_id = $_GET['party_id'];
	$party_status = "Not Confirmed";
	
	$stmt = $link->prepare("UPDATE `party_form` SET `party_status` = ? WHERE `party_id` =  ? LIMIT 1");
	$stmt->bind_param("si", $party_status, $party_id);
	$stmt->execute();
	$stmt->close();
	$link->close();
        echo '<script type="text/javascript">alert("Success!")</script>';
	}
}	

Open in new window

0
 
Dave BaldwinFixer of ProblemsCommented:
If you use a <script> tag on the page to load something from PHP, the code should not have a second <script> in it.  It's the same rules as loading any external javascript file, you don't put <script> tags in the file.
0
 
Ray PaseurCommented:
There is a timeline of request and response that might be in play here (I've been drinking beer and watching football games, so I'm not going into deep analysis).  It works like this:

1. Client makes a request.
2. Server makes a response.

The request is atomic, complete, and stateless.  Everything that the client knows is sent with the request (URL parameters, POST variables, if any, HTTP cookies).  After the request, the client sits idle and waits for the server response.

The response is also atomic, complete and stateless.  Using only the information from the client, and information that was already stored on the server, the server formulates and sends the response.  The response is usually instantaneous.  Then the server disconnects, forgets about the client, and waits for another request.

The response document is typically HTML - a web page.  It may also include CSS and JavaScript.  As the response is received by the client, the JavaScript instructions are executed immediately upon receipt.  But (and this is a bit "but") there is no further interaction between the client and server until the client sends another request.  If the JavaScript causes another request, that's a separate interaction, and is logically unrelated to the original request.

Details about this protocol are available in this article:
https://www.experts-exchange.com/articles/11271/Understanding-Client-Server-Protocols-and-Web-Applications.html

So to the original question: "Is it possible to store jQuery in a PHP variable and echo it?" the answer is "yes" but anything that is to be done by the jQuery script must be considered a separate HTTP request.
0
 
Kim WalkerWeb Programmer/TechnicianCommented:
First, I don't see an jQuery in your code unless the function swal is somehow related to jQuery.

The question is where does the function cancel_party_booking() get executed? If it is executed during the dynamic page composition, it should be inserted in the source code and execute the javascript swal() function during the initial loading and parsing of the page in the browser. It should be visible in the source code.
0
 
Nainudhin AfrozCommented:
Hello,
What i observed here is that you are trying to use sweet alert from php. But php code is compiled before your html / Jquery is compiled. So when u call SWAL , this function is not yet defined as the supporting classes are not yet loaded during the function call.

Alternatively you can call the popup first and then load the page with your php code.

Hope this helps.
0
 
Ray PaseurCommented:
For the purpose of simplified testing, you can substitute native JS alert() for SweetAlert.  

If the function call is in open text (not encapsulated inside a function) both functions will be run as soon as the browser receives the JavaScript.

If the function call is encapsulated inside a function both functions will be run when the browser reacts and calls the JavaScript function, usually in response to an HTML event.

This may save you some time testing, and remove any complexity associated with SweetAlert.  Not sure if there is any complexity, unless there is some interaction between PHP and the content of the Alert objects, but it might be worth considering.
0
 
Julian HansenCommented:
From what I can tell you are trying to show a response message after sending data to the server and updating the database.

Here is how a PHP page works

1. A URL is requested Example http://www.domain.com/mypage.php
2. The webserver recognises the .PHP extension as being handled by another process and passes it off to the PHP engine
3. PHP engine parses the file and executes the code in it
4. Script produces output which is sent back to the browser
5. PHP script terminates and ceases to play any further role in this process
6. Browser receives output as it would any normal page - it does not know that the output was
produced by a PHP script.
7. Browser processes returned text
  a) If it is an HTML element it renders it
  b) if it is an external resource (img, css, javascript file etc) it initiates an asynchronous request to fetch the resource - this means it continues to process the document while the requested resource downloads in the background.
  c) If it is script that exists outside of a Document Ready block it executes it
      i) Any script that tries to act on an element that comes after it in the document will fail as the element does not exist yet
     ii) Any script that requires an external resource to run where the resource has not loaded yet will fail.
       Example: if script outside of a Document Ready block tries to initiate a Sweet Alert and the Sweet Alert javascript file is still downloading then this operation will fail with an error.
  d) As load events for resources downloaded asynchronously fire the script / css / image etc is applied / added to the document.
   e) Once all resources have downloaded the document enters a ready state and the scripts registered to run on document ready are executed.

In your case what is happening is you are outputing script in your PHP function but without taking into account where that script is going to run in the above process.

If the function you have showed us is part of other output functions that all contribute to the output of the document then the ordering of those output statements is important.

It looks like you are wanting to produce a status popup from a database operation. In which case you should be considering AJAX as the means to achieve this. You send the update request to the server by AJAX and in your server code you process that request and compile a return object to send back to the browser. The sending script processes this return (in which you might include a status flag and a message) and the AJAX call back function creates the Sweet Alert.

Without seeing the function in context of your complete code - it is difficult to say what you should be doing.
0
 
Slick812Commented:
greetings Black Sulfur, , You have already gotten many good explanations and code factors from the experts here. I looked at your javascript code on this file -
          https://limonte.github.io/sweetalert2/dist/sweetalert2.js

and I could not find any  XMLHttpRequest (for AJAX) or any  references to any AJAX server exchange. As others have said here, to do the the mysqli PHP code like -
       $link->prepare("UPDATE `party_form` SET `party_status` = ? WHERE `party_id` =  ? LIMIT 1");

from a browser page using javascript operations, , you will need to do a javascript server request and response using the JS XMLHttpRequest Object.

If you are not familiar with using the XMLHttpRequest ( AJAX ) , then my main message to you is it may be much more complicated to integrate the AJAX into your popup Alert add-on. This is because you will have to use server side code, which your Sweet Alert download may not be able to set up on another persons web host. You may can have example code to show an AJAX call to server, but it may not be just javascript code? ?
0
 
Black SulfurAuthor Commented:
Wow, thanks so much to everyone for the comments. I will read through them tomorrow evening. I was hoping to go through them all this evening but I got home too late now. I at least wanted to reply to everyone though. Thanks again. Will post back tomorrow.
0
 
Black SulfurAuthor Commented:
Hi all,

Thanks again for the comments. Just to clarify a few things, it is correct to say that I am trying to get a sweet alert popup to appear after completing a database operation. I want the record to update in the
database and the popup to appear afterwards to confirm the update has taken place.

My initial thinking was that I should be using AJAX, but as some of you know, I am new to even PHP and I am trying to get to grips with one thing at a time. Some users on Experts Exchange have already assisted me with some AJAX questions I had but to be honest, trying to learn PHP together with AJAX was confusing to me as some of the things I had just learnt in PHP now had to be done differently to accommodate AJAX.

So, I thought maybe I could use php to call the sweet alert without going the AJAX route but it seems that it is even more complicated that way, haha!

I think the best thing I can do for now is set a success message with a session variable and just display that until such time as I move onto AJAX. Reading between the lines, I think AJAX is the only way to go here unless I am yet again missing the point everyone is making.

And as much as I really appreciate everybody's feedback, I now have the impossible task of splitting points :P
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.