Jquery Ajax Post Error Undefined in Codeigniter - php

I am implementing a jquery ajax form submission on selecting the checkbox. I am always getting error undefined in the response data. Please find my code as following.
Jquery Post
$.ajax({
type: "POST",
url: filelink+"playlist/add_cart_item",
data: {"product_id":id,"quantity":qty,"ajax":1},
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(textStatus + " " + errorThrown)
}
});
Controller Function
function add_cart_item(){
echo "true";
}
File link is giving me the exact path. Jquery library file is also properly included. Can anybody please help where could be the problem.
I am using HMVC Codeigniter. Is there any other way of calling php file from ajax in it ??
Also When I am changing the type from POST to GET it is returning my ECHO "TEST" ..
Thanks

Several points.
in add_cart_item() try adding the correct header for json data
Try to use console.log instead of alert for debugging javascript.
Try to debug the http request/response using firebug.

You had an insecure ajax call..ill recommend this way
$.ajax({
type: "POST",
url: filelink+"playlist/add_cart_item",
data: {"product_id":id,"quantity":qty,"ajax":1},
success: function(msg){
alert( "Data Saved: " + msg );
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(textStatus + " " + errorThrown)
}
});
function add_cart_item(){
echo $_POST['product_id'];
exit;
}

Related

Ajax: I can't get data from PHP by using json_encode

I am having issues retrieving data from PHP by using Ajax. I am stuck and have been spending lots of time trying to find out where the problem is.
Here is my php code:
<?php //ajax/default_chart_numbers.php
require_once '../core/db_connection.php';
$lotto = new Lotto();
$ultimo_concurso=$lotto->ultimo_concurso('foo');
$ultimos_numeros_m=$lotto->ultimos_numeros('bar');
$R1m=$ultimos_numeros_m[1];
$R2m=$ultimos_numeros_m[2];
$R3m=$ultimos_numeros_m[3];
$R4m=$ultimos_numeros_m[4];
$R5m=$ultimos_numeros_m[5];
$R6m=$ultimos_numeros_m[6];
$R7m=$ultimos_numeros_m[7];
//preparing json
$json=array('y'=>$ultimo_concurso,'n1'=>$R1m,'n2'=>$R2m,'n3'=>$R3m,'n4'=>$R4m,'n5'=>$R5m,'n6'=>$R6m);
print json_encode($json,true);
?>
The output of the PHP file is:
{"y":"2745","n1":"1","n2":"13","n3":"19","n4":"29","n5":"41","n6":"46"}
And here is the jQuery code:
<script>
$(document).ready(function(){
/*Retriving data from PHP file*/
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (response, textS, xhr) {
alert("everything ok :)");
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
},
complete: function(data){
y=data.y;
alert('The id number is '+ y);
}
});
});
</script>
When executing, the value is undefined. I mean, the alert i get is The id number is undefined.
What am i missing?
There's no true in json_encode, there is in json_decode to get an array, but now you're creating a string
change
print json_encode($json,true);
to
echo json_encode($json);
and the complete handler doesn't get the data, it has two arguments, the XHR object and the statuscode, the success handler gets the data
$.ajax({
url: "ajax/default_chart_numbers.php",
cache: false,
dataType: "json",
timeout:3000,
success : function (data) {
y=data.y;
alert('The id number is '+ y);
},
error : function (xmlHttpRequest, textStatus, errorThrown) {
alert("Error " + errorThrown);
if(textStatus==='timeout')
alert("request timed out");
}
});
On PHP side, send the JSON with:
header('Content-Type: application/json');
echo json_encode($json);
Maybe log the incoming data to the console:
inside success: add an console.log(response)
inside complete: add an console.log(data.y)
This is missing:
https://api.jquery.com/jQuery.parseJSON/
try using:
result = $.parseJSON (data);
result.y has your value

Ajax form not being submitted

I am attempting to send a very simple login form from a jQuery Modal form.
$( "#dialog-form" ).dialog({
var url = "../scripts/sign_up.php";
$.ajax({
type: "POST",
url: url,
data: $("#dialog-form").serialize(),
success: function(data){
alert("it works")
}
});
});
This is my first real shot at trying Ajax and I am having issues getting the success method to go through. I have checked that my script is in the right place and that the dialog_form has the right id.
Am I sending this information incorrectly? Is there a good way to troubleshoot Ajax requests?
Right now I am just trying to get the info to go through and, to simply the question, removed other code for the form.
First, I might reccommend adding an error function to your Ajax request as well - it may help with error handling:
error: function (jqXHR, textStatus, errorThrown) {
alert(textStatus);
alert(errorThrown);
}
Second, how are you sending data back from the script to the Ajax request? If you're not echoing back any data from your script, the request is not going to know that the script ran sucessfully.
Therefore, you may want to add the following to your AJAX call:
dataType: "json",
And then return data from your PHP script like so:
$data = array("success"=> true);
echo json_encode($data);
exit;
In full (using your script):
$( "#dialog-form" ).dialog({
var url = "../scripts/sign_up.php";
$.ajax({
type: "POST",
url: url,
dataType: "json",
data: $("#dialog-form").serialize(),
success: function(data) {
if (data.success) {
alert("it works")
}
else {
alert("it failed, but no server error!");
}
}
error: function (jqXHR, textStatus, errorThrown) {
alert("server error");
alert(textStatus);
alert(errorThrown);
}
});
});

PHP script not running from Jquery/AJAX?

I am trying to pass the user's checked HTML radio button value to a PHP variable using Jquery/Javascript and Ajax.
The following is a simplified version of the HTML/Javascript:
$("input[name=bus_plan]").on('change', function(){
var $postID = "=" + $('input:radio[name=bus_plan]:checked').val();
$.ajax ({
type: "GET",
url: "product-group.php",
data: {"postID" : $postID },
success : function(data){
alert("done");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("problem: " + errorThrown);
}
});
});
The ajax call shows a success (i.e. there is a "done" alert.)
This is the product-group.php:
<?php
echo "hello world<br>";
$postid = $_GET['postID'];
echo "The postID is ".$postid;
?>
Any help in understanding/fixing the fact that product-group.php does not appear to run would be most appreciated.
Thank you.
Try alert(data) instead of alert("done") to see if jQuery is receiving the correct response.
Your echo output is in "data" var, its like the "return" for ajaxcalls.
Tru alert(data) or append the data content on some div.
Try rewriting your ajax call like this-
$("input[name=bus_plan]").on('change', function(){
var postID = $('input:radio[name=bus_plan]:checked').val();
$.ajax ({
type: "GET",
url: "product-group.php?postID="+postID,
success : function(data){
alert("done");
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("problem: " + errorThrown);
}
});
});

Ajax POST-request doesn't come through to PHP

I'm firing an HTTP POST request with Ajax to my php file, but I don't get the desired result. $_POST and $_GET are both empty. I think I'm overlooking something, but I have no clue what.
Here's my code for firing the request:
this.save = function() {
alert(ko.toJSON([this.name, this.description, this.pages]));
$.ajax("x", {
data: ko.toJSON([this.name, this.description, this.pages]),
type: "post", contentType: "application/json",
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
};
Note that I alert the JSON on line 3. That JSON is correct, so the input on line 5 is valid.
My test method in PHP:
header('Content-type: application/json; charset=utf-8');
echo json_encode(array_merge($_POST, $_GET));
exit;
The response I'm getting is an empty array.
I tested the input (see above);
I know the Ajax call itself succeeds, if I replace that second line in my PHP example with json_encode(array('success' => true)); I get that back in my page - so the URL is correct.
I tested it with both GET and POST, with similar negative results.
You are sending a JSON request, that's why both $_POST and $_GET are empty. Try sending the data like this:
$.ajax("x", {
data: { data: [this.name, this.description, this.pages] },
type: "post",
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
Now look inside $_POST["data"].
or if you need to use a JSON request then you need to deserialize it back in your PHP file:
$.ajax("x", {
data: { data: ko.toJSON([this.name, this.description, this.pages]) },
type: "post",
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
and then decode:
$json = $_POST['json'];
$data = json_decode($json);
and if you want to send pure JSON request in the POST body:
$.ajax("x", {
data: ko.toJSON([this.name, this.description, this.pages]),
type: "post",
contentType: 'application/json',
success: function(result) { alert(result) },
error : function(jqXHR, textStatus, errorThrown) { alert(textStatus + errorThrown)}
});
and then:
$data = json_decode(file_get_contents("php://input"));
Notice that php://input is a read-only stream that allows you to read raw data from the request body.

Making value from PHP show on page requesting AJAX data

I have a simple login form and it does return the "success" text in the function, but now I want to be able to add the text provided in the .php file. How can I do this?
html
<script>
$(function(){
$("#submitlogin").click(function() {
inputs = {
"logInUsername" : $('input[name=logInUsername]').val(),
"logInPassword" : $('input[name=logInPassword]').val()
};
// since this is a username and password combo you will probably want to use $.post
$.ajax ({
type: "POST",
url: "loggnow.php",
data: inputs,
success: function() {
$("#login").html("You are now logged in!");
},
error : function(jqXHR, textStatus, errorThrown){
alert("error " + textStatus + ": " + errorThrown);
}
});
});
});
$.ajax({
type: "POST",
url: "loggnow.php",
data: inputs,
dataType: "html",
success: function (data) {
$("#login").html(data);
},
error : function (jqXHR, textStatus, errorThrown) {
alert("error " + textStatus + ": " + errorThrown);
}
});
The docs on jquery web sites says that the sucess function will be passed the data. (See quoted). So you can just use the content passed back in the "data" variable, and put it in there.
success(data, textStatus, jqXHR)
A function to be called if the request succeeds. The function gets passed
three arguments: The data returned from the server, formatted according to
the dataType parameter; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success
setting can accept an array of functions. Each function will be called in
turn.

Categories