script doesn't load after ajax response - javascript

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) ;
}

Related

PHP json_encode add a 1 to the end of the string

I'm using json_encode throughout my project without issue, except in one instance.
I make an ajax call from one page, as I do in others, and the resulting json appends a 1 to the end of the string for some odd reason.
My return string looks like this
{
"overtime": "yes"
}1
What could be causing this? I have literally commented everything out of the class that returns this string and I simply have the following code.
$reservation = ['overtime' => 'yes'];
return json_encode($reservation, JSON_PRETTY_PRINT);
My ajax request looks like this
$.ajax({
type: 'POST',
url: "{{ URL::action('Controllers\\PurchasesController#calculateReservation') }}",
data: { 'arrive' : arrive, 'depart' : depart},
dataType: 'json',
success: function(response) {
alert(response);
}
});
The alert doesn't fire and doesn't display anything as the json is invalid with the 1 appended to the end of the string.
You should echo the response from your controller, rather than returning it:
echo json_encode($reservation, JSON_PRETTY_PRINT);
In some scenarios (for example using WordPress), it is also necessary to call die() afterwards, as well.

Ajax's data parameter not making it to the server

Okay here's my problem.
I have an html page that has a javascript variable initialized in it.
<html>
<script>
MyVaribale = "Random Data";
</script>
<!-- Then I include an external js file to handle the processes in this html file -->
<script type="text/javascript" language="javascript" src="/scripts/some_random_script.js"></script>
</html>
Now, inside that script. I used the MyVaribalevarible in one of the ajax request there, like this :
$(document).ready(function() {
$.ajax(
url : '/some/random/url',
data : { MyVariable : MyVaribale }
etc ...
);
});
So, on page load, that ajax code is executed immediately.
In the url specified above, i checked for the existence of MyVaribale, then flag an error that it is a required value if it doesn't exist.
Backend code like this (in Perl):
my $MyVariable = trim_param('MyVariable'); # trim_param() is a function that gets the passed data from ajax.
if ( $MyVariable ) { # Test if it exists
# Display something
}
else {
# Flag an error, which is my problem
}
Now I am sure that in the html page, that variable is always populated (yes 100% sure). But I always get flag errors that that value doesn't exist in my backend code (url above).
So question,
Does ajax have some issue with document.ready, maybe it executes before the variable has finished assigning a value? Any idea why this happens? Because sometimes my ajax request is successful, sometimes it's not
Thanks
The syntax of your ajax call is not correct. Have a look here and then try this code (note the addition of {, } and ,):
MyVaribale = "Random Data";
$(document).ready(function() {
$.ajax({
url: '/some/random/url',
data : { myVariable : MyVaribale }
});
});
Did not you try out some complete ajax calls? Like this.Sometimes no need to use JSON.stringify for MyVariable.
$.ajax({
url: "/some/random/url",
type: 'POST',
dataType: 'json',
data: JSON.stringify(MyVaribale),
contentType: 'application/json',
mimeType: 'application/json'
}).done(function(data) {
}).fail(function(error) {
}).always(function(){
});

jQuery AJAX reload specific div

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');
}

accessing jquery variable in PHP in same page

I want to access javascript variable in php of the same page.
I'm doing a AJAX call and I get a JSON data.
This AJAX call is being fired upon a dropdown change.
I wanted to run few PHP functions on the same in the AJAX function based on the dropdown value.
$.ajax({
type: "POST",
url: "data.php",
data: { dropdown1: dropdown1,
variable2: variable2
},
async: true,
dataType: 'json'
}).done(function(result) {
// chart functions
<?php
$dropdown_val = $_POST['dropdown1']
?>
})
Is it possible that I can send the form value inside of the page itself to PHP function?
Suggest me please...
Unfortunately this isn't possible. You'd have to run another AJAX call and put your PHP inside that. Alternatively, couldn't you put the PHP inside the data.php file and run it from within that?

Using the JQuery Ajax function to Return 2 Sets of Data

I'm using the JQuery AJAX function to deliver data to a PHP doc.
Currently, the AJAX success function returns HTML which gets added to the html page.
My goal is for the success function to return a second/different piece of data that can be used as a JavaScript variable.
How can this be done?
Update
The question was answered correctly. Here is an example of the resulting script.
PHP Document
<?php
$some_html = 'foo';
$some_value_for_js_variable = 'bar';
// create json content
echo "{";
echo "\"some_html_outupt\":\"$some_html\",";
echo "\"some_value_for_js_varialbe_output\":\"$some_vale_for_js_variable\"";
echo "}";
?>
JS Document
// Jquery ajax function
$.ajax({
dataType: 'json',
type: "POST",
url: "some_file.php", // the location of the above mentioned php script
cache: false,
success: function(json) {
$(el).html(json['some_html_output']); // add html output to page
var a = json['some_value_for_js_varialbe_output']; // assign value to js varialbe
}
}
}); // ajax
The way that I would implement this is to return the data in a JSON string with 2 items in it The first part would hold the HTML and the 2nd part holding the data for the variable that you want.
{"html":{html},
"2nd variable":"{data}"}
and then you can do a $.getJSON call to your web server like
$.getJSON('path','querystring=if_needed',function(data){
var html = data['html'];
var 2ndVariable = data['2nd Variable']
//do other things that you want
});
I hope that helps

Categories

Resources