Passing JSON object to PHP script - javascript

I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.

without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php

Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.

As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.

Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);

Related

How to get data in PHP from AJAX jQuery request

So I've followed all your advice about making an jQuery or Javascript AJAX request to a php file on a server.
The problem I'm running in to is that my response is this
Fatal error: Array callback has to contain indices 0 and 1 in
So here is my jQuery
$(document).ready(function(){
$(".ex .select").click(function(){
$("body").data("id", $(this).parent().next().text());
Those lines serve to capture a variable and save it as data on the body element, so I can use it later.
But I want to send that same variable to PHP file, to add to a complex API request - eventually to return the results, create $_SESSION variables and so forth
var pageId = {
id: $("body").data("id"),
};
But let's avoid that as a problem and just make my array simple like
var pageId = {
id: "12345",
};
$.ajax({
type: 'GET',
url: 'test.php',
data: pageId,
datatype: 'json',
cache: false,
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
});
});
And for now at least I was hoping to keep my PHP file simple for testing my grasp of the concepts here
<?php
$id = $_GET('id');
echo json_encode($id);
?>
I'm expecting the response
Data: 12345
Status: Success
But I get the Error Message above.
You need to change $_GET('id') to $_GET['id']
and in order to send status, you need to add status to an array just like below and try to parse JSON on your response.
<?php
$id = $_GET['id'];
$result = array("id"=>$id, "Status"=>"Success");
echo json_encode($result);
?>
And access in jquery using . like if you use data variable in success then
success:function(data){
alert(data.Status);
}
change $id = $_GET('id'); to $id = $_GET['id'];
because $_GET, not a function it's an array type element.

Call Php controller function with AJAX Codeigniter

I , im working with Ajax and Codeigniter to call function client-server
the php
public function mainViewClean() {
unset($_SESSION[$this::jsondevices]);
unset($_SESSION[$this::jsontags]);
return "Ready";
}
//route $route['cleantags'] = 'user/mainViewClean';
And ajax:
<script type="text/javascript">
$(document).ready(function(){
$("#btn_recargar").button().click(function(){
//window.location.href = "<?= base_url('home')?>";
$.ajax({
type:'POST',
url:'<?php echo base_url("cleantags"); ?>',
data:{'id':100},
success:function(data){
//window.location.href = "<?= base_url('home')?>";
alert(data);
}
});
});
});
</script>
The function excuse good , but javascript don't show any data , what im doing wrong?
Well, the ajax call reads the response from the server, and that response must be rendered as some type of readable data, such as application/json or text/html.
In order to write that data, you need to echo it from the server with PHP.
The return statement doesn't write data, it simply returns at the server level.
If you want to communicate between PHP functions, you have to use return. But if you want to output some data, you have to use echo
Client side
$.ajax({
url:'<?php echo base_url("cleantags"); ?>',
dataType: 'application/json',
success:function(response)
{
alert(response.foo);
}
})
Server Side
public function mainViewClean()
{
unset($_SESSION[$this::jsondevices]);
unset($_SESSION[$this::jsontags]);
echo json_encode( array("foo"=>"Ready"));
}
Change return into :
echo "Ready";
If you're sending an array, at server side you need to json_encode, example :
// encode array into json string format
echo json_encode( array( 'name' => 'Osman' ) );
And in Js, you have 2 options, the 1st solution is :
success : function ( data ) {
// data now is coming in this form { "name" : "osman" }
// as the string data is coming from server-side
// you must parse it back into Javascript object
var newData = JSON.parse( data );
}
And the 2nd option is, add dataType properties inside ajax properties like following :
$.ajax({
...
dataType : 'json', // with this, no need to write JSON.parse()
...
});
I'm fairly new as I only have been using AJAX , but I think your code has a few syntactical errors.
data: { id:100 } with no quotations around id.
I advise you need to look at more examples of ajax calls to fix these little errors.
You said your JS is working but not showing data?

Sending a javascript variable to a PHP script using jQuery Ajax

I'm trying to send a JavaScript variable to a php script using ajax. This is my first time using ajax and I don't know where I went wrong. Here's my code
function selectcat(v) {
$.ajax({
type: "GET",
url: "myurl.php",
dataType: "script",
data: { "selected_category" : v}
}).done(function() {
window.location.href = "http://mywebsite.com";
});
}
All help is appreciated
Here's the HTML
<ul class="cat">
<li class="opt" onclick="selectcat('option1')">option1</li>
<li class="opt" onclick="selectcat('option2')">Option 2</li>
</ul>
This is the ajax php file
<?php
session_start();
$ctgry = $_GET['selected_category'];
$_SESSION['select_cat'] = $ctgry;
?>
You need to remove dataType: "script" since you are just sending data. Do it like this:
function selectcat(v) {
$.ajax({
type: "GET",
url: "myurl.php",
data: {"selected_category": v}
}).done(function(result) {
console.log(result);
//window.location.href = "http://mywebsite.com";
});
}
Hi this is what I do to call an ajax request
You can post data or load a file using following code:
$("#button click or any other event").click(function(){
try
{
$.post("my php page address",
{
'Status':'6',
'var one':$("#myid or .class").val().trim(),
'var 2':'var 2'
}, function(data){
data=data.trim();
// alert(data);
// this data is data that the server sends back in case of ajax request you
//can send any type of data whether json or or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
I hope this help!
AJAX is easier than it sounds. You just need to see a few good examples.
Try these:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
The above examples demonstrate a few things:
(1) There are four formats for an AJAX request - the full $.ajax() structure, and three shortcut structures ($.post(), $.get(), and $.load() )
Until you are pretty good at AJAX, I suggest using a correctly formatted $.ajax() code block, which is what the above examples demonstrate. Such a code block looks like this:
$('#divID').click({
$.ajax({
type: 'post',
url: 'contact.php',
dataType: 'json',
data: 'email=' + form.email.value
}).done(function(data) {
if ( typeof(data) == 'object' ) {
if ( data.status == 'valid') {
form.submit();
} else if(data.status !=='valid' {
alert('The e-mail address entered is wrong.');
return false;
} else {
alert('Failed to connect to the server.');
return false;
}
}
});
});
(2) In an $.ajax() code block, the data: line specifies the data that is sent to the PHP processor file.
(3) The dataType: line specifies the type of data that the ajax code block expects to receive back from the PHP processor file. The default dataType is html, unless otherwise specified.
(4) In the PHP processor file, data is returned to the AJAX code block via the echo command. Whether that data is returned as html, text, or json, it is echoed back to the AJAX routine, like this:
<?php
//perform MySQL search here. For eg, get array $result with: $result['firstname'] and $result['lastname']
$out = '<div id="myresponse">';
$out .= 'First Name: <input type="text" value="' .$result['firstname']. '" />';
$out .= 'Last Name: <input type="text" value="' .$result['lastname']. '" />';
$out .= '</div>';
echo $out;
Please try a couple of the above examples for yourself and you will see how it works.
It is not necessary to use json to send/return data. However, json is a useful format to send array data, but as you can see, you can construct a full html response on the PHP side and echo back the finished markup.
So, you just need to echo back some data. It is the job of the PHP file to:
(1) receive the data from the AJAX routine,
(2) Use that data in a look up of some kind (usually in a database),
(3) Construct a response, and
(4) echo (NOT return) the response back to the AJAX routine's success: or .done() functions.
Your example could be changed to look something like:
HTML:
<ul class="cat">
<li class="opt" value="TheFirstOption">option1</li>
<li class="opt" value="The Second Option">Option 2</li>
</ul>
javascript/jQuery:
$('.opt').click(function(){
var v = $(this).val();
$.ajax({
type: "POST",
url: "myurl.php",
dataType: "html",
data: { "selected_category" : v}
}).done(function(data) {
$('#div_to_insert_the_response').html(data);
});
});
PHP:
<?php
$val = $_POST['selected_category'];
echo 'You selected: ' . $val;
dataType: "script" has no sense here, I think you want json or leave it empty.
Your PHP script should work if you try to get the variable with $_GET['selected_category']
I suggest you this modification to help yourself for debugging
$.ajax({
type: "GET",
url: "myurl.php",
data: { "selected_category" : v},
success: function(data){
console.log(data);
// you can also do redirection here (or in complete below)
},
complete: function(data){
// when request is done, independent of success or error.
},
error: function(data){
// display things to the user
console.error(data);
}
})

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

Undefined index: Error in ajax POST and/or php script?

I'm trying to send an ajax POST to a php file, however the php file sends a notice of "undefined index", and the php file never seems to receive the value i'm trying to send it. I've been searching for the answer to why this isn't working correctly, so hopefully someone can give me some insight.
My javascript function receives a value from the html, and receives the correct value. (it's "1" in this case)
function deleteMediaFromDatabase(val)
{
$.ajax({ url: 'deleteMediaFromDatabase.php',
data: {vals : val},
type: 'post',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
}
Here is part of my php file that should receive the post:
<?php
ini_set("display_errors", "On");
error_reporting(E_ALL);
$val = $_POST["vals"];
// create connection
$con = mysqli_connect(<stuff you don't care about>);
error_log($val . ' is the value', 3, "./error.log");
?>
I am, however getting this error message from php:
Notice: Undefined index: vals in
/xxx/xxx/htdocs/AdminPanel/deleteMediaFromDatabase.php on line 9
And my javascript always outputs the alert in the error: "Error: Could not delete"
I know this question has been asked and answered many times, however unless I'm skipping over something small, my code, to me, looks correct. (but doesn't it always...)
There is error in syntax of jquery.. You missed out syntax of data. This should be like this-
function deleteMediaFromDatabase(val)
{
$.ajax({ url: 'deleteMediaFromDatabase.php',
data: {'vals' : val},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error: Could not delete");
}
});
}
The problem can come from the dataType not being specified or that the dataType specified does not match thus returned by the server.
Explicitely set the dataType, e.g.
dataType:'json'
and make sure that your script returns data that is "encoded" in the data type that you chose, e.g. in PHP:
echo json_encode($something);
Instead of:
$val = $_POST["vals"];
use this:
if (isset($_POST['vals']) {
$val = $_POST['vals'];
}
Change Ajax syntax...
$.ajax({
type: "POST",
url: 'deleteMediaFromDatabase.php',
data: {'vals' : val},//Have u tried this
success: function(output) {
alert(output);
}
error: function(request, status, error){
alert("Error: Could not delete");
}
);
$val = $_POST["vals"];
I got same problem , i tried declaring the variable as global , that solved my problem.
global $val;
$val = $_POST["vals"];
and always check isset($_POST["vals"])

Categories