AJAX call to PHP receives the "previous" posted data - php

So I post data from a form using the jQuery form extension. This code is executed when the user presses ["Save"] on the HTML page.
$('#myform').ajaxForm({
async: false,
cache: false,
target: $(this).find('.save-response'),
beforeSubmit: function(arr,$form){
json_ = JSON.stringify (vars.table_settings[aux.getTableId()].by_ix); //, null, 4);
$form.find('.user-settings').val(json_);
$form.find('.save-response').stop(true,true).hide().show();
alert (json_);
},
success: function(){
$(this).fadeOut(15000);
},
As you see, I use the alert() function to check what is actually being delivered in the AJAX call, to the destination PHP file. What I see is the following:
[
...
{"id":"colpartdesc","vis":"vis","width":500,"ix":3,"desc":"Part Desc."},
...
]
On the PHP file, I read the $_POST value, and feed it back to the calling page (to the .save-response element in this example) as a response. What I get as a reply is this:
[
...
{"id":"colpartdesc","vis":"vis","width":270,"ix":3,"desc":"Part Desc."},
...
]
As you see, the "width" value is different. In fact, a value of 270 is the value that I sent the last time I pressed the ["Save"] button. If I press ["Save"] again, the server will receive the 500 value sent in this call. But it may be that the value of 500 is wrong by that time.
If I press the ["Save"] button twice each time before changing the input, then the functionality works as expected.
As you see, I've disabled the cache in the Ajax call, so I don't think this is the problem.
Does anyone have an idea why I am experiencing this behaviour?
Aside: the original HTML page is generated using Smarty templating engine. However, I have switched off caching in the Smarty engine too, so again, I don't think this is significant. Also, the PHP file processing the Ajax call does not use a Smarty template.

The answer to the problem is that I don't know how the jQuery Form plugin works.
jQuery Form does not submit the values in the fields of the form, but rather the value in the array. Therefore, updating the values in the form itself withing the beforeSubmit function (as done in the following line) is incorrect:
$form.find('.user-settings').val(json_);
What I should be doing instead is to update the form-data array, like this:
$('#myform').ajaxForm({
$(this).ajaxForm({
target: $(this).find('.save-response'),
beforeSubmit: function(formData,$form){
json_ = JSON.stringify (vars.table_settings[aux.getTableId()].by_ix); //, null, 4);
formData[1].value = json_;
$form.find('.save-response').stop(true,true).hide().show();
},
success: function(){
$(this).fadeOut(15000);
},
});
The answer to >>this<< post is what put me on the right tracks.

Related

jQuery does 2 loads... and returns 500 error

For some reason my jQuery AJAX request submits the first POST successfully, but then it causes a second GET which does not submit the post data, causing a Index Undefined error. When viewing the logs with Firebug, I see it does the first POST successfully posting the data I want to submit, but then it does a second GET request pulling the entire "SecondPage.php" file without posting any data, overriding the DIV it was set to display in.
Here's the code:
$(document).on('change', '.SubmitRadioButton', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'SecondPage.php',
cache: false,
data: $(this.form).serialize(),
success: function(html) {
window.alert('Successfully submitted AJAX request!');
$("#DIVinFirstPage").load("SecondPage.php");
}
});
return false;
});
What am I doing wrong?
Also - I have noticed that on this second PHP page I have to make a reference to my "Header.php" file that performs all the functions. Why is it that with this ajax request, it doesn't inherit all the rules from the page as a PHP include("File.php") does? Is there any way around this so I don't have to re-initialize and re-download all the PHP and JavaScript files? I tried include_once("File.php") in the PHP and that didn't correct it either.
jQuery load is the same thing as doing a $.get request. Is only a wrapper.
.load()
So you are basically doing a post request with some data on this part of the code
$.ajax({
type: 'post',
url: 'SecondPage.php',
cache: false,
data: $(this.form).serialize(),
success: function(html) {
window.alert('Successfully submitted AJAX request!');
And then inside the success making a get request to the same page on this line.
$("#DIVinFirstPage").load("SecondPage.php");
Then the page SecondPage.php is giving you an Index Undefined Error because SecondPage.php is expecting POST data which is not being sent in the .load call.
Since the Index Undefined is a php error, that sends the 500 error code to the browser.
So you need to either check if the variables are set using isset on SecondPage.php or make the load call another page that is not expecting any data.
Another alternative would be to have the script that handles the POST on a separate php file and then do the .load to the second page of your form.
In the success callback of the first POST request, you perform a JQuery load(). According to documentation http://api.jquery.com/load/, "It is roughly equivalent to $.get(url, data, success)".
You see your success callback function has a parameter named "html". That is the response served to your from SecondPage.php after the POST request. I imagine that contains the content you want to populate your div with.
Perhaps try:
success: function(html) {
window.alert('Successfully submitted AJAX request!');
$("#DIVinFirstPage").html(html);
}

jquery post to a php page with javascript or php

I have one quick question for experienced ones.
I have a page that does a jquery ajax post to another php page with javascript in it.
My question is, will the javascript get executed as well?
Another question.
lets say, that instead of javascript, I have another jquery ajax post request to a third php.
Will any of the 2 work?
Unless the javascript in that "another php page" is actually returned to the client and somehow inserted into the DOM, the JS cannot and will not execute. The resulting output of an AJAX operation is returned as a string to the code that performed the ajax call. It's not interpreted/parsed except in a few very specific cases.
If you're using jQuery's AJAX function to send POST variables to a PHP file, only the backend code will be executed. However, upon success of the AJAX call, you can execute some more JS code as follows
//Define whatever variables you want to pass along to the PHP file
var variable = "";
$.ajax({
url: "file.php",
type: "POST",
data: "variable="+ variable,
success: function(data)
{
//Upon success of the call, you can execute JS code here
}
});
Additional info here

jQuery .post() to refresh the pages PHP-variables without whiteout in Cake PHP

I got a problem and I´m about to hurt the MVC-paradigm, so I rather ask you what to do.
I got a page which is refreshed every 10 seconds with jQuery .post()-method.
setInterval(function() {
$.post("http://XYZ.de<?php echo $this->webroot."Posts/index"; ?>", { liveUpdate: "true" },
function(response) {
$('#loadingContent').html(response);
}
);
}, 10000);
now, where the "Posts/index" is placed I have to call the PostsController.php of Cake which allows me to reset the variables.
But it doesn´t work that way and the response is filled with all the html of a normal page-call but I only want to have the pure PHP-variables updated without html appended to that div.
What am I doing wrong?
Thanks in advance for your patience.
Since your array is complex multilevel and you do not want to parse JSON, the only way I see doing it would be using jQuery load().
setInterval(function() {
jQuery("#RefreshMeOnPage")
.load("http://XYZ.de<?php echo $this->webroot."Posts/index"; ?> #RefreshMeInResults > *", {liveUpdate: "true"});
}, 10000);
It will make post request to server and replace contents of existing element with id RefreshMeOnPage with the contents of newly received element with id RefreshMeInResults. Docs http://api.jquery.com/load/.
NOTE: Still with refresh rate of 10 seconds, I think you should look into ajax comet solution http://cometdaily.com/maturity.html. It will receive data only when there is change, although it requires some configuration.

pjax submit form URL redirection

PJAX's documentation states that Github uses $.pjax.submit() in submitting a Gist form. A desired feature of an ajax form submission which Github nicely implements is that the URL redirects from the form's action to a newly created URL (in this case, one containing the newly server-side created gist ID).
For example, from this:
https://gist.github.com/gists // form action
to this:
https://gist.github.com/tim-peterson/5019589 //assume this ID is generated server side
I've gotten this to work similarly on my site (i.e., the page itself redirects to the equivalent of https://gist.github.com/tim-peterson/5019589) but I can't redirect the URL (it stays like https://gist.github.com/gists).
Is this entirely a server-side issue (setting headers?) or is there something in pjax that I'm missing? I'm using a version of pjax I downloaded today so it can't be that i'm using a buggier version of pjax.
Did you find any solution to this?
I had the similar issue.
Basically you need to set X-PJAX-URL property in response header.
It's value should be same as Request URL.
In Laravel, I did it like this...
App::after(function($request, $response)
{
$response->headers->set('X-PJAX-URL', $request->getRequestUri());
});
There may be a more-elegant / proper way to do this with $.pjax.submit(), but this is the solution I've been using without any problems. I serialize the form inputs prior to submission, then POST them to my server. Then check the reply from the server to make sure I don't need to prevent the user from going forward before calling my PJAX to continue.
$("#save").click(function(e) {
e.preventDefault();
dataString = $("#form").serialize();
$.ajax({
type: "POST",
url: $("#form").attr("action"),
data: dataString,
dataType: "json",
success: function(data)
{
// Handle the server response (display errors if necessary)
$.pjax({
timeout: 2000,
url: data.url,
container: '#main-content'
});
}
});
});
It happens if response HTML doesn't contain initial PJAX container

PHP reload page when adding forms (maybe needs ajax)

Sorry for maybe incorrect title for the topic, but this is the best that I came up with.
So, I'm building admin panel for a website.
I have a page, and in some part of the page, i'd like to refresh it and load another form.
let's say add a schedule, and somewhere down on the page I'd like to have this form displayed as soon as the link is clicked.
when a user saves it, I'd like that form to disappear and and in stead of that to have a list displaying all of the schedules.
I don't want to use frames - I'm not a supporter of frames. The panel is built using PHP.
Maybe this might be achived with Ajax? If yes -> How? any link to good example or tutorial.
yes this will be solved with ajax.
Here is a code example when the page is supposed to refresh
$('#button').click(function() {
$.ajax({
url: 'path/to/script.php',
type: 'post',
dataType: 'html', // depends on what you want to return, json, xml, html?
// we'll say html for this example
data: formData, // if you are passing data to your php script, needed with a post request
success: function(data, textStatus, jqXHR) {
console.log(data); // the console will tell use if we're returning data
$('#update-menu').html(data); // update the element with the returned data
},
error: function(textStatus, errorThrown, jqXHR) {
console.log(errorThrown); // the console will tell us if there are any problems
}
}); //end ajax
return false; // prevent default button behavior
}); // end click
jQuery Ajax
http://api.jquery.com/jQuery.ajax/
Script explained.
1 - User clicks the button.
2 - Click function initiates an XHR call to the server.
3 - The url is the php script that will process the data we are sending based on the values posted.
4 - The type is a POST request, which needs data to return data.
5 - The dataType in this case will be html.
6 - The data that we are sending to the script will probably be a serialization of the form element that is assigned to the variable formData.
7 - If the XHR returns 200, then log in the console the returned data so we know what we are working with. Then place that data as html inside the selected element (#update-menu).
8 - If there is an error have the console log the error for us.
9 - Return false to prevent default behavior.
10 - All done.

Categories