So I'm learning Ajax and I followed this tutorial: https://phpacademy.org/course/submitting-a-form-with-ajax to create a function that works for any form. This is the complete function:
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
alert(url + ' ' + response);
}
})
return false;
});
As you see all I'm doing is alerting the response, which in this case is php echo. That's where my problem starts, I need a flexible and secure way to handle the javascript/php communication. Preferrably one function for all forms, maybe with if () statements instead of alert(url + ' ' + response); depending on the form url.
The function I need is not very complicated, based on the response I get I will just update the current form with errors.
Aslong as I know what to use in the communication I'm fine from there, echo '1'; as I have now doesn't feel like the ideal solution but it's all I could handle.
So, what type of response should I send from the php page, and where (in the javascript) and how is the best way to handle it? I've heard of json but having a hard time wrapping my head around it. Could someone show a json response sending a basic integer thats easy for my response to pick up as an int?
You can send back a simple JSON response via PHP and check it in your success callback. Make sure you're setting the type to json and in your AJAX call, and using json_encode on the PHP side:
$response = array('response' => 1);
echo json_encode($response);
Output should be:
{ 'response' : 1 }
Related
I have an application that after performing a search, returns me multiple "fieldsets" with some hidden inputs (via AJAX!).
I want to use these inputs to send information to the server (again) via AJAX.
The names of these inputs are automatically listed with a prefix:
"video_url_1", "video_url_2", etc.
When the user clicks the button, the value of "video_url_1" or "video_url_2" will be sent via AJAX depending on the button to which it has clicked. To solve this I got the name of the button that was clicked and then I cut the name so that I only have one number, this number I put in a variable and then use it in the "data" section of AJAX.
I did the test by sending a locally stored input and it worked but when trying to send the inputs that were previously obtained by an ajax, it does not work.
What can be wrong? This is my code:
$(document).ajaxComplete(function(){
$('a.report_video').click(function() {
var idbutton = $(this).attr('id');
var idreport = idbutton.replace('report_video_', '');
//I'm still not using these variables, can they be used to pass the input data to ajax?
var videourl = $("#video_url_" + idreport).val();
var videoid = $("#video_id_" + idreport).val();
var videoserver = $("#server").val();
///////////
$.ajax({
type : 'POST',
url : 'https://example.com/script/script.php',
data : $($("#video_url_" + idreport)).serialize(), //It doesn't work
//For example, data: $("#server").serialize()
//Work fine, this input is stored locally.
beforeSend: function(){
$('#video_report_' + idreport).html('<img src="'+pluginUrl+'./assets/img/loading.svg" />');
}
}).done(function(data) {
$('#video_report_' + idreport).html(data);
});
return false;
});
});
Edit:
I just did some tests as suggested by Kevin B and I see that the problem I have is in the syntax when trying to send two dynamic ID's by Ajax.
The problem is that I do not know how to write them correctly, I know that is the problem because when I tried to send them separately they did work...
data : $($("#video_id_" + idreport), $("#video_url_" + idreport)).serialize(),
I'm not sure I completely understand your problem, but this might help.
You call your second AJAX call in the .success() method of the first AJAX call. Essentially chaining the responses.
$('#btn').click(function() {
$.ajax({
type: "POST",
url: 'someURL',
data: someData
}).done(function(firstCallData) {
// This OPTIONAL method fires when the AJAC call succeeded
// You can also put another AJAX call in here with the data returned from the first call
$.ajax({
type: "POST",
url: 'someURL',
data: firstCallData
}).done(function(data) {
// Do something with second AJAX call with data
}).fail(function(data) {
// Second AJAX call failed, handle error
});
}).fail(function(data) {
// This OPTIONAL method fires when the first response failed
}).always(function(data) {
// This OPTIONAL method fires regardless if the first call succeeded or failed.
});
});
I've researched this, but it's hard to find something when you don't know the best way to do it or even how to begin. I don't have any code obviously, so i'll describe my issue and hopefully someone can point me to the correct way to solve this :
ok let's say I have a page with a javascript function called "myfunction1" that fires off every x seconds by using setinterval in js. What I want it to do is, (using AJAX perhaps?) when "myfunction1" is called, call a php script that will check something in the database. If a certain condition is TRUE, I want a specific function to be called in javascript on the client side. If FALSE, I want it to call a different function.
My intuition makes me think the way to do it is to have the ajax call the php checking script, then echo the proper javascript code based on if true or false. But how would I go about doing that? I know how to use ajax to change the .innerhtml of a tag, but can you use it in this way to rewrite inside a script tag?? My head's spinning, hope I made some sense and one of you can point me the right way
AJAX would probably be the simplest solution and can be used to evaluate returning script or you can manually validate/display the response from the XmlHttpRequest that the server processed.
For example when using jQuery.ajax You can change the dataType option to script.
Otherwise you can manually program the validation in the success callback, like below, using JSON.
javascript (jQuery)
jQuery(function($) {
'use strict';
var element = $('#myElement');
var ajax = null;
var ajaxTimeout = 0;
function myFunction1() {
if (null !== ajax) {
//prevent overlapping ajax requests
ajax.abort();
ajax = null;
}
ajax = $.ajax({
url: '/response.php',
method: 'post',
dataType: 'json',
success: function(data) {
//parse the server side response
if (data.result === true) {
trueFunction(data);
} else {
falseFunction(data);
}
ajax = null;
}
});
}
//custom functions for true or false and setInterval.
function trueFunction(data) {
element.html('Success: ' + data.value);
}
function falseFunction(data) {
element.html('Failed: ' + data.value);
}
ajaxTimeout = window.setInterval(myFunction1, 1000);
});
response.php
<?php
header('Content-Type: application/json');
$date = new \DateTime;
echo json_encode((object) [
'value' => 'Hello World ' . $date->format('Y-m-d h:i:s a'),
'result' => true
]);
exit;
Hi im having a problem refreshing my page when a condition is met in php using ajax, if the php script is successful i want it to reload the page but when it is not then i only want to echo the errors.
The following is the part of my PHP code that returns the 'success' or error message:
if ($login) {
echo "success";
} else {
echo '<p>Username and Password does not match</p>';
};
This is working as i have tested it separately and the user gets logged in even though ajax
The problem i think comes in the ajax call back with the if statement.
Here is the my js script that is running the ajax call back.
$('form.ajax').on('submit', function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
if(response == "success") {
//location.reload();
window.location = "index.php";
} else {
$('#loginError').html(response);
};
}
});
return false;
});
I have tried everything on the net but every time the PHP script is successful it just echo's out the word success rather then redirecting the page or reloading
Thanks chris85 for the perfect advice worked like gold and was able to fix the problem, that was that there was a extra line at the top of my PHP script that I missed and saw it when i used console.log(response), also read the post you linked and it will help with future problems like this for me so thanks again.
I want to store my javascript output in PHP. I mean, my js code is:
function loadCurrentUser () {
var url = APIPATH + 'load_current_user.php' ;
var result = $.ajax({
type : "GET" ,
url : url,
async : false
}). responseText ;
var resultJSON = processJSONResult(result);
}
What I want is to store the output I received (in json format) to my variable $json (in php). How can I do that?
based on the comments above it cannot be done as you think. But if you insist on getting response date to a php variable you will have to make another ajax call as ajax call occur at client side and php runs in your server not on the browser #briosheje had explained it nicely. may be what you need is session variable ($_SESSION['index']) to store your response data
so I'm doing a basic assignment for uni, they asked us to use ajax and php to create a text input that validates the name and email plus a live search bar, all this without using db. So I have the html already set up, the .php with 3 different arrays with names, emails and news stored in and a main.js that already displays whatever you type in the text input in the console with the keyup event trigger. I just can't figure out a way to make an ajax request to compare what you type in to the info stored in the arrays.
In the arrays.php I have this :
*$classes = array('1' => 101, '2'=> 102, '3'=>103 );*
*$names = array('juan', 'tito', 'pedro', 'horacio', 'andres', 'cesar', 'nicolas');*
*$news = array('Title'=>array('El papa muere', 'Argentina gana el mundial', 'Fondos buitres cancelados' )'Noticia'=>array('noticia1', 'noticia2', 'noticia3')
);*
and in the main.js I have something like this:
$('#name').keyup(function(){
var name=$(this).val();
console.log(name);
that retrieves what I type in each text field. As far as I can remember, the prof wrote something like this to give us a hint:
$.ajax({
url: ' ',
type: ' ',
success:function(data){
}
}):
But I just can't figure it out so any help would be much appretiated!
The general idea is to pass the current value of the search box to your PHP script via ajax. Then in your PHP script, you would filter your options based on the current value passed to it and return a filtered response. The javascript would then take the filtered response and output it on the page.
People usually use JSON as a format for passing information between Javascript and PHP.
To give you a little better understanding what $.ajax does. It will make a request to your server and then process the results. The parameters specified do the following:
url: The URL to request
type: The format of the response (eg. text, xml, json, etc.)
success: A callback to be called when the response comes back from the response.
Also note that the A in AJAX stands for asynchronous. This is why you need to give the $.ajax function a callback. Due to the nature of HTTP, you make a request and the response can return right away or in 30 seconds or never. When the response returns the callback will execute. It is not linear. Therefore the callback can execute after code below the the $.ajax call depending on how long it takes for the response to come back.
Maybe take a look at the example below to give you a better idea of how to do this:
<?php
$names = array('juan', 'tito', 'pedro', 'horacio', 'andres', 'cesar', 'nicolas');
$result = array();
foreach($names as $name)
{
if (strpos($name, $_GET['name']) !== false)
{
$result[] = $name;
}
}
echo json_encode($result);
?>
And the javascript
$('#name').keyup(function() {
var name=$(this).val();
$.ajax({
url: '?name=' + name,
type: 'json',
success: function(data) {
console.log(data);
// add data to results
}
}):
});