jQuery AJAX reload specific div - javascript

I have the following code, as part of a code to add some value to a database.
After executing the $.ajax succesfully, I want a specific div (with class 'lijst') to be reloaded with the refreshed data.
$.ajax({
url: \"frontend/inc/functions/add_selectie.php\",
type: \"POST\",
data: ({ 'p_id' : p_id, 'v_id' : v_id, 'pd_id' : pd_id }),
cache: false,
success: function()
{
$(\".lijst\").hide().fadeIn('slow');
}
});
However, with this solution, only the div is refreshed, not the actual PHP variables that are specified in there. When I refresh my browser manually, the values are updated.
How can I refresh the div and also update the variables?

According to the jQuery.ajax documentation, the function signature of "success".
Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server ...
So in other words:
success: function(data) {
$(".lijst").html(data).hide().fadeIn('slow');
}

Actually, the PHP variables specified in the html are worked at the sever part. PHP variables in the html have replaced by the string of there value when it is ready to be sent to the browser. And your ajax request will cause PHP to update database. So when you have sent the request and then refresh the page, PHP will replace the varables in the html again.
According to this above, your ajax request and the server repsonse are not aware of the PHP variables's existence. So you must update the content yourself.
Maybe you will do something like this:
success: function(data) {
$(".lijst").hide();
$(".title").html(data.title); // $(".title") may be a tag that surround a PHP variable
$(".content").html(data.content); // the same as $(".title")
$(".lijst").fadeIn('slow');
}

Related

script doesn't load after ajax response

I was trying to make an ajax call and show an html part inside a div class. For that i used the following way.
$.ajax({
type: "get",
url: "{{url('searchByCheckbox')}}",
dataType: 'html',
success: function(html)
{
$(".infinite-scroll").html(html)
}
});
But the problem is there is a script inside that html part which i wanted to load when i make first ajax call it's not loaded but for the second one it's loaded the script.
suppose the html response like this :
<script>
alert()
</script>
// html
How do i make it work?
I put the script above the html page which i'm getting as response.
(those who are marking the Question as duplicate should read at least what i want and what they wanted )
Im sure that the error is happening because of the script, because you are closing the </script> tag inside the html.
The best solution is to return the data from your ajax call as a json
To do that you should:
1- add a dataType to your ajax parameter as the below:
$.ajax({
type: "get",
dataType: "json",
2- In the php file handling the ajax call, you must resurn the values as a json as below:
Assume that currently you are doing the following:
echo $html
You should change it to match the below:
$retArr = array(
"html" => $html, //Your html code without the javascript function
"jsFunc" => $jsFunc //Your java script function parameters
) ;
echo json_encode($retArr) ;
And then your ajax success must be as the below:
success: function(data)
{ //You can access all the object parametes by calling the object name `data` followed by a dot `.` and then by the parameter key
data.jsFunc // Your javascript function params
$(".infinite-scroll").html(data.html) ;
}

Return variable from PHP after AJAX Post

I've read countless examples but I just can't get the following to work. I want to submit a form, process it on the server side then decide which php script to load into a div (dynamic loading I can do).
The head:
$.ajax({
type: "POST",
url: url, // passed with onclick
data: $("#" + formName).serialize(),
success: function(data) {
// Some JSON? to go here to store variable returned from PHP ($thisVariable)
}
});
return false; // avoid to execute the actual submit of the form.
The php:
// Process the request (add to database e.g.)
$thisVariable back to ajax

jQuery onClick pass a variable via GET to URL and load that URL

I know how to pass variables through AJAX calls via onClick to a PHP file and asynchronously loading the results on the initial page.
I now need to analogously pass a variable via onClick to a PHP file but I need to open a new window or redirect the whole page with the passed variable. The URL needs to contain the variable, so that the query/results can be "statically" sent to someone, like 'xyz.php?var=xyz'
I thought I could do something like this
$("#submit").click(function(event) {
var category_id = {};
category_id['linkgen'] = $("#linkgen").val();
$.ajax({
type: "GET",
url: "generatedlink.php",
dataType: "html",
data: category_id,
success: function(response){
window.open('generatedlink.php');
}
});
});
This only opens 'generatedlink.php'. I actually want what is passed via AJAX, i.e. 'generatedlink.php?linkgen=blabla' onClick in a new window/reloaded page! I'd very much appreciate your help.
just try: without ajax call
$("#submit").click(function(event) {
window.open('generatedlink.php?inkgen='+$("#linkgen").val());
});

Return info from jQuery AJAX call and execute additional jQuery on success

I have the following jQuery AJAX to duplicate a background image. I am stumped as to how to effectively return information back to the original page. Here is the AJAX I send on click of "'#dupBtn"...
//DUPLICATE BACKGROUND
$('#dupBtn').click(function() {
jQuery.ajax({
type: "POST",
dataType:'json',
url: "../system/bgUpdate.php",
data: {
"user":<?= $_POST['user'] ?>,
"bgID":bgID,
"refID2":<?= $_POST['refID2'] ?>,
"refTable":"<?= $_POST['refTable'] ?>",
"bgTitle":($('#bgTitle').val()),
"path":path,
"bgColor":bgColor,
"bgPoz":bgPoz,
"bgRepeat":bgRepeat,
"attach":attach
}
});
});
Here is the basic MySQL query on the PHP page bgUpdate.php.
mysql_query("INSERT INTO backgrounds (user,title,path,bgColor,bgPosition,bgRepeat,bgAttachment) VALUES ('".$_POST['user']."','$title','".$_POST['path']."','$bgColor','".$_POST['bgPoz']."','$rt','$attach')");
$bgIDnew = mysql_insert_id();
What I want to do is have the following code fired on the original page upon successful execution of the MySQL entry, dynamically catching the '$bgIDnew' from the MySQL PHP page.
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
You can accomplish this with the success attribute of the .ajax() function:
$('#dupBtn').click(function() {
jQuery.ajax({
type: "POST",
dataType:'json',
url: "../system/bgUpdate.php",
data: {
...
},
success:
function(response)
{
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
});
});
That's only part of it though... The other half is that your PHP needs to return something that jQuery can understand as a "successful" call. My preference is to use HTTP status codes. In your case, your PHP script should return a 200 code if it was successful; otherwise, it should return something in the 400 range. (By the way, if you want jQuery to do something separate with errors, you can use the error property of .ajax().)
However, if you need to return data from the server to the client-side script, then your PHP can print out that information like this:
mysql_query("INSERT INTO backgrounds (user,title,path,bgColor,bgPosition,bgRepeat,bgAttachment) VALUES ('".$_POST['user']."','$title','".$_POST['path']."','$bgColor','".$_POST['bgPoz']."','$rt','$attach')");
$bgIDnew = mysql_insert_id();
// Best practice to keep it in some sort of understandable format
// Here, we'll put it in an associative array:
$response = array('id' => $bgIDnew);
print_r(json_encode($response));
This PHP script sends back to the ajax() method a JSON representation of the $response variable. You've already configured that ajax() method to read the response dataType as JSON, so it already knows how to read the response parameter... Which means your success function can look something like this:
success:
function(response)
{
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=' + response.id);
}
jQuery.ajax() has a success property that acts as a callback that you can use. Another is complete which is fired if the request is successful or not.
jQuery.ajax({
/* your stuff here */
success: function(response) {
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
});
You can write up the logic in the success callback function of your ajax Request..
This is fired when an ajax request is successfully returned..
success: function(response) {
$('#bgPickerBox').load('../dialog/bgPickerAlbums.php?album=<?=$bgIDnew?>');
}
Add this to your ajax Request...

Multiple AJAX Call and JSON data

I have designed a website that takes a users input as search parameters and uses them to search a database using an AJAX call to a PHP page. In this AJAX call, I obviously have some data (formatted as a JSON file) that I manipulate and use in the "success" section of the ajax arguments.
Here's the problem--I want to be able to analyze the data from the narrowed search the user puts in against the data from the entire database population. How can I do this?
I thought I would just do another AJAX call, but the data from that call seems inaccessible from the outside, and I can't find any ways to "export" it outside the call.
Here is a shortened version of the code:
$.ajax({
url: URL for the search .php,
cache: false,
data: {
Various search parameters by the user
},
dataType:"json",
success:function(data){
Data manipulation and reading the resulting JSON
$.ajax({
url:URL2 for the population .php,
cache: false,
dataType:"json",
success:function(data){
population data stuff here
},
error: error stuff
}
error: error stuff
}
That's the only way I know to access the database thus far. How can I somehow pull the data out of that second AJAX so that I can use it in the first one?
Since your working with asynchronous callbacks you can't "extract" the data from the second call and use it in the first. What you will have to do is make the two calls and use the data from each within the second calls success callback. You can do this if rename the variables you're using with the success callback functions to be unique.
$.ajax({
url: /**/,
success:function(response1){
$.ajax({
url: /**/,
success:function(response2){
/* use both response1 and response2 here */
},
error: /**/
})
},
error: /**/
})
If you aren't using data from the first ajax call to make the second ajax call you can use something like jQuery.when to wait for both request to finish.

Categories

Resources