I don't understand how the success function works in a $.ajax call with jquery.
for instance
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
useReturnData(data /* ??? not sure how to use the data var */ );
}
};
ajax.php:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
?>
how do i use that data within the success function? No where seems to explain what the data parameter is, they just seem to use it ambiguously.
another side question, is the data: "function=1" related to the data as a parameter for the success function?
The data variable contains the output of your php file, so if in your php file you do:
echo "<p>success</p>";
data will contain <p>success</p>.
In your example you would change your php file to:
<?php
if ($_REQUEST['function'] == '1'){
$string = "this is the data i want to return and use";
}
// other stuff...
echo $string;
?>
The content of the data parameter depends on the type of the response. If the Content-Type is application/json, then it's parsed as JSON. If it's text/html or similar, the content is HTML. In your case, it looks like you're returning text. If you make your Content-Type header text/plain or similar, then data should just be a string.
To answer your second question, the data property for the Ajax request is something different; it specifies the request data that is sent. In other words, it's the query string if you have a GET request, and the post "form" variables if it's a POST request.
data is whatever is returned by the server side script, so in this case it would be
this is the data i want to return and use
Providing the if() condition is met.
Nobody really says what data contains because it can contain various different things, although it's always a string. Sometimes it's HTML, sometimes it's JSON and sometimes just a return message.
In your case, data will just be a string providing you echo the string out in your server side script.
The easiest way is to load the data into some placeholder element (div?)
E.G.
$.ajax({
type: "POST",
url: "ajax.php",
data: "function=1",
success: function(data,response,jqxhr){
$('div.selector').load(data);
}
};
Related
EDIT
I simplified the array that I was trying to JSON encode in php script. The returnArr in php script now has only one key, value pair and still I am getting invalid character error:
PHP script:
$returnArr["a"] = "val";
er('Content-type:application/json;charset=utf-8');
echo(json_encode($returnArr));
I am trying to return an array(in the form of key=>value) to my ajax call from the server side php script. Ajax receives the response but is unable to parse the JSON data returned by server. Gives error "Invalid character" on the line where I am parsing the returned data inside ajax success function.
Below is my server side script:
$returnArr = Array();
header('Content-Type: application/json');
foreach($selectUpdatedRecord as $eachRow)
{
$key = $eachRow['cat_id'];
$htmlStr = '<td>'.$eachRow["cat_id"].'</td>
<td>'.$eachRow["cat_name"].'</td>
<td>
<select name="statCat-catId-'.$eachRow["cat_id"].'" disabled="disabled">
<option value="'.$eachRow["cat_status"].'" selected="selected">'.$eachRow["cat_status"].'</option>
<option value="Enabled">Enabled</option>
<option value="Disabled">Disabled</option>
</select></td>
<td>'.$eachRow["created_at"].'</td>
<td><button type="submit" id="save-cat-'.$eachRow["cat_id"].'" name="save-cat-'.$eachRow["cat_id"].'" class="btn btn-info save-ind">Save</button></td>
<td><input type="checkbox" class="select_cats" name="cat_edit_array" value="'.$eachRow['cat_id'].'"></td>
';
$returnArr[$key] = $htmlStr;
}
echo json_encode($returnArr);
FYI, the $key is numeric and the $htmlStr variable will hold some table cells with values. I would use the $key to identify some unique rows and populate the rows with the corresponding html content. the console.log() call is just a test to see whether parsing is successful.
And here is the ajax function:
$.ajax({
type: "GET",
url: "ajax_catEdit_loader.php",
data:{'get_updatedData':sendDataToAjax},
success: function(returnedText) {
console.log(JSON.parse(returnedText)); //--->error on this line
error: function(xhr, status, error) {
alert("failed");
console.log("ajax failed: "+error);
}
});
I have tried to include the datatype: as JSON in the ajax call and omit the JSON.parse call but still same result.
Would really appreciate some help.
The problem was indeed in JSON.parse, however, there is a bit more to it than that.
Problem-1: JSON.parse method is expecting string as argument. So instead when you provide an Array or Object, you'll get the error. Check the following example CODE:
var obj = {};
try {
JSON.parse( obj );
}
catch( err ) {
console.error( err );
}
Problem-2: Now, the second problem is NOT json_encode() in PHP as you've probably understood it. Because json_encode() PHP function is indeed returning String. However, since you are sending JSON MIME type header:
header('Content-Type: application/json');
jQuery is receiving it as a JSON object.
By default, PHP returns output as html, so if you remove the header, the error will not be there. So clear browser cache & try by removing the header or by using any one of the following headers:
header('Content-Type: text/plain');
// or the default one:
// header('Content-Type: text/html');
Problem-3: You also need to understand the dataType property of jQuery ajax function.
According to the documentation, dataType is defined as:
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
So, when you are not specifying the dataType, jQuery is automatically getting it as JSON because of your MIME type header. Thus, even when you specify:
dataType: 'json',
the same problem doesn't go away. Now guess what will happen if we specifically tell jQuery to receive data as text:
dataType: 'text',
You've probably guessed it right. Once we mention that we want to receive the data as text, even if in PHP we send JSON MIME type header, jQuery will consider it as text and JSON.parse will execute without error.
Note: while you test by changing the header, remember that browser will cache the result. So you'll need to clear browser cache every time you test with a new header or call the script with an additional random query string like this:
url: "ajax_catEdit_loader.php?rand=" + Math.random(),
You can also check what type of data browser is receiving (as html, as text, as json etc.) from the Network panel of the browser's Developer Tool (Data type will be shown in the Type column).
My PHP is outputting data like this:
$data['full_feed'] = $sxml;
$data['other_stuff']= $new;
echo json_encode($data);
So, in my jQuery, I'm doing this.
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
console.log(data['full_feed']);
});
This comes back undefined. So does console.log(data.full_feed). I'm getting back from PHP a valid JSON object, but missing how I can "parse" it correctly.
Parse "data" parameter in response with jQuery.parseJSON function. Then use parsed.full_feed value. Like below:
$.ajax({
url: 'untitled.php',
type: 'GET',
success: function(data) {
data = jQuery.parseJSON(data);
console.log(data.full_feed);
});
You can do like #tilz0R said or for your example to work you need to tell the browser you are sending a json response. So need to set content type header like
header('Content-Type: application/json');
echo json_encode($data);
to see what the server is returning do console.log(typeof data). If its a string you need to parse it. if its an object, it is already parsed.
Also you can put dataType:'json' in your ajax call to let jquery know you are excepting a json response.
I am trying to to extract a Json response in jquery sent from a php file.
This is the .js code:
$.ajax({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
datatype: 'json',
data: {'userCheck': username},
success: function(data){
// Check if username is available or not
},
error: function(){
alert('Much wrong, such sad');
}
});
This is the response from the php file:
if($sth->fetchColumn()!=0){
//$response = array("taken");
$response = array("username"=>"taken");
echo json_encode($response);
//echo '{"username':'taken"}';
}else{
//$response = array("available");
$response = array("username"=>"available");
echo json_encode($response);
//echo '{"username":"available"}';
}
I have tried all combinations I can think of in both files, but nothing seems to work. It is a simple check for a username in the database. If I console log the data I get from the response, I get this:
{"username":"available"}<!DOCTYPE html>
// The rest of the page html
So the info is there, but how do I access it? I have tried several syntaxes found around the internet, but no luck so far. I seem to recall that a json response only can contain valid json, so is the problem the html? I don't think I can avoid this due to the structure of my application, so hopefully it is possible to access the json with my present structure.
in you Ajax
EDIT:
change
datatype:"json",
the case of parameter name was not respected, the t must be T
dataType:"json",
now retry please
$.ajax
({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
dataType: 'json',
data: {'userCheck': username},
success: function(data)
{
// Check if username is available or not
switch(data.username)
{
case "available":
// do you want
break;
case "taken":
// do you want
break;
}
},
error: function()
{
alert('Much wrong, such sad');
}
});
in PHP
simply that, and don't forget to exit; to avoid include html page in your json response !
This is the code coming after the }".... who break your json output
and make it unreadable by javascript (worste, it simply break your javascript !)
echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]);
exit;
When you're responding to an AJAX call, you should just return the JSON response, not the HTML of the page. Add:
exit();
after this code so you don't display the HTML after the JSON.
In the JS code, use if (data.username == 'available') to tell whether the username is available.
The other problem in your code is that you have a typo here:
datatype: 'json',
It should be dataType, with an uppercase T.
You can also put:
header("Content-type: application/json");
before echoing the JSON in the script, and jQuery will automatically parse the response.
Also you can set request headers in your jQuery ajax call beforeSend function like follows
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Accept', 'application/json');
}
So you're strictly declaring the data type to be json
Im on project to make an app with codeigniter but i got stuck, when i want to pass same variable outside field via ajax into controller i got error the variable is not defined.
this is a example.
$("#form_status_update").submit(function() {
var date = new Date().toString();`
$.ajax({
type: 'POST',
url: "<?php echo base_url()?>socialcontroller/setdate",
data:date,
success: function(data) {
window.location.href = "<?php echo base_url()?>socialcontroller/ssetdate";
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //throw any errors
}
});
});
after passing some var i want to insert into my database.
and my question is how to pass a variable not field into controller via ajax thanks, i already search on google but i didnt geting the right answer :)
`
The line data:date, is wrong. You are passing up a number on the querystring and not a key/value pair.
It needs to be
data: {date : date},
or
data: "date=" + encodeURIComponent(date),
From jQuery Docs:
data
Type: PlainObject or String or Array
Data to be sent to the
server. It is converted to a query string, if not already a string.
It's appended to the url for GET-requests. See processData option to
prevent this automatic processing. Object must be Key/Value pairs. If
value is an Array, jQuery serializes multiple values with same key
based on the value of the traditional setting (described below).
Here is the code that help you with your problem
You can just adapt it with your code and it should work !
<script>
$(document).ready(function(){
$("button").click(function(){
var myDate = new Date();
$.ajax({
// Send with POST mean you must retrieve it in server side with POST
type: 'POST',
// change this to the url of your controller
url:"index.php",
// Set the data that you are submitting
data:({date:myDate}),
success:function(result){
// Change here with what you need to do with your data if you need of course
$("#div1").html(result);
}});
});
});
</script>
<body>
<div id="div1">
<p>Today date here</h2>
</div>
<button> Get Date< /button>
</body>
</html>
and your PHP code can be something like this !
<?php
// This line of code should get your data that you are sending
$data = $_POST['date'];
/// This code was just for checking purpose that it is returning the same value through ajax
$arr = array(
'receive_date'=>$data,
);
echo json_encode($arr);
I think this code can work with must of MVC framework if you are setting your controller URL as url parameter. Check also the Framework documentation about getting the data through POST !
your selector $("form_status_update") doesn't match a class or an id of the DOM.
and it doesn't match an html element either.
so this for sure gives you some (extra) problems.
couldnt you have tried running the date function at the php controller youre calling from the ajax function.
i dont see any specific reason as to why you have to send in date as the input parameter from the javascript function.
remove the date var and data field.
and in your php controller.
when you get the controller called.
run a date function in the php code and use the date from there.
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
}
}):
});