I have the following jquery code that posts data to a php file and works fine on localhost. But when this code is now on the server the script returns an error instead of data.
$.ajax({
type: 'POST',
url: 'scripts/info.php',
data: {
accountNumber: accountNumber,
agentName: name
},
success: function( data ) {
alert(data)
},
error: function(xhr, status, error) {
// check status && error
alert(status)
}
});
This is the code in the php file that handles the post request:
$args0 = array(
'accountNumber' => $_POST['accountNumber'],
'dateReceived' => date("Y-m-d"),
'firstNames' => $_POST['agentName'] '
'regNumber' => $_POST['accountNumber'],
'surname' => $_POST['agentName']
);
try {
$client = new SoapClient(WSDL_URL, array(
'trace' => 1,
'exceptions' => true,
'connection_timeout' => 300));
$params = array(
'arg0' => $args0,
);
$client->__setLocation(WSDL_LOCATION);
$response = $client->upload($params);
$response = $client->__getLastResponse();
echo $response;
Please help
$.ajax({
type:"post",
url:"/pay/index.php?submit_order=yes",
dataType:'json',
data:{
'rmb': $('#rmb').val(),
'couponid': $('#cid').val(),
'title' :$('#title').text(),
'user' :$('#user').text(),
'phone' :$('#phone').text(),
'code' :$('#code').text(),
'size' :$('#size').text(),
'isinvoice':$('[name=isinvoice]').val()
},
beforeSend:function(){
beforeSend.attr('disabled',true);
beforeSend.html('submitting').removeAttr('href');
},
success:function(data){
if(data.errorcode==1){
$('.pay-fail').show().text(data.message);
}else{
if(data.url){
location.href=data.url;
}else{
alert('post ok!');
}
}
},
error: function(){
alert('submit error,then try again');
}
})
This is my jQuery ajax for pay. It works on localhost and on server.
Related
I'm having problems updating a record with an image. I don't what I need to do. My image is stored in a public folder called 'img/products'
ProductController.php
This is my controller. It works well without modifying the image.
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price_neto' => 'required',
'iva' => 'required',
'price_total' => 'required',
'image' => '',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$products = Product::find($id);
$products->name = $request->input('name');
$products->category_id = $request->input('category_id');
$products->description = $request->input('description');
$products->price_neto = $request->input('price_neto');
$products->iva = $request->input('iva');
$products->price_total = $request->input('price_total');
$products->image = $request->input('image');
$products->save();
return response()->json([
'error' => false,
'products' => $products,
], 200);
}
Product.js
All I know is that I have to use var formData = new FormData ($ ("# frmAddProduct") [0]); as in the store function. I can enter records with images but not edit them. My image is stored in a public folder called 'img/products'
$(document).ready(function() {
$("#btn-edit").click(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'PUT',
url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),
data: {
name: $("#frmEditProduct input[name=name]").val(),
category_id: $("#frmEditProduct select[name=category_id]").val(),
description: $("#frmEditProduct input[name=description]").val(),
price_neto: $("#frmEditProduct input[name=price_neto2]").val(),
iva: $("#frmEditProduct input[name=iva2]").val(),
price_total: $("#frmEditProduct input[name=price_total2]").val(),
image: $("#frmEditProduct input[name=image]").val(),
},
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
});
function editProductForm(product_id) {
$.ajax({
type: 'GET',
url: '/product/' + product_id,
success: function(data) {
$("#edit-error-bag").hide();
$("#frmEditProduct input[name=name]").val(data.products.name);
$("#frmEditProduct select[name=category_id]").val(data.products.category_id);
$("#frmEditProduct input[name=description]").val(data.products.description);
$("#frmEditProduct input[name=price_neto2]").val(data.products.price_neto);
$("#frmEditProduct input[name=iva2]").val(data.products.iva);
$("#frmEditProduct input[name=price_total2]").val(data.products.price_total);
$("#frmEditProduct file[name=image]").val(data.products.image);
$("#frmEditProduct input[name=product_id]").val(data.products.id);
$('#editProductModal').modal('show');
},
error: function(data) {
console.log(data);
}
});
}
You should check if the file exists before trying to delete, for example:
$product = Product::find($id);
if(!$product)
{
return response()->json(['error' => 'Product not found'], 404);
}
if (Storage::disk('local')->exists('img/products/'.$product->image)) {
Storage::disk('local')->delete('img/products/'.$product->image);
}
Take a look one example only:
public function update(UpdateProductFormRequest $request, $id)
{
$product = Product::find($id);
$data = $request->only('name','category_id','description',
'price_neto','iva','price_total');
if(!$product)
{
return response()->json(['error' => 'Product not found'], 404);
}
// when saving the file, delete the old file first
if ($request->hasFile('image')) {
$file = $request->file('image');
$original_filename = $file->getClientOriginalName();
// $mime = $file->getMimeType(); // Suggestion
$extention = $file->getExtension();
// $size = $file->getClientSize(); // Suggestion
$stored_filename = $original_filename; // md5($original_filename); // Suggestion
$file_path = storage_path('public/img/products/');
if (Storage::disk('local')
->exists("public/img/products/{$stored_filename}.{$extention}"))
{
Storage::disk('local')
->delete("public/img/products/{$recordSet->stored_filename}.{$extention}");
}
$file_moved = $file->move($file_path, "{$stored_filename}.{$extention}");
$data->image = "{$stored_filename}.{$extention}";
}
// Updating data
$result = $product->update($data);
if ($result) {
/* return redirect()
->route('products.index')
->withSuccess('Product was successfully updated'); */
return response()->json([
'message' => 'Product was successfully updated'
'product' => $product
]); // You don't have to put 200 because it's the default
}
/* return back()
->withErrors(['Unable to update the product'])
->withInput($request->input()); */
return response()->json(['error' => 'Unable to update the product'], 400);
}
It would be better if you create a form request to do your validations.
Don't forget to create links to the storage path:
php artisan storage:link
I think it would be helpful:
$("#btn-edit").click(function() {
var formData = new FormData($("#frmAddProduct")[0]);
formData.append('_method', 'put');
formData.append('_token', "{{ csrf_token() }}"); // if you are using Blade
var route= "{{ route('products.update', ['id' => ':id']) }}"; // if you are using Blade
route= route.replace(':id', $("#frmEditProduct input[name=product_id]").val())
$.ajax({
method: 'post',
url: route,
data: formData,
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
Is your js script in "Blade" ? If so, try it this way:
var image = '{{ asset("/img/products/_image_file") }}'
image.replace('_image_file', data.products.image)
$("#frmEditProduct file[name=image]").val(image)
Note that we can first use the "asset ()" helper to create the full path to use to find the image, but with a "_image_file" placeholder
After that, we use the replace () function to change the "_image_file" placeholder with the actual image file brought from the ajax response.
Something like this?
ProductController.php
public function update(Request $request, $id)
{
$validator = Validator::make($request->input(), array(
'name' => 'required',
'category_id' => 'required',
'description' => 'required',
'price_neto' => 'required',
'iva' => 'required',
'price_total' => 'required',
'image' => '',
));
if ($validator->fails()) {
return response()->json([
'error' => true,
'messages' => $validator->errors(),
], 422);
}
$products = Product::find($id);
if ($request->hasFile('image')) {
$productImage = $request->file('image');
$productImageName = rand() . '.' . $productImage->getClientOriginalExtension();
if (Storage::disk('local')->exists("img/products/{$productImageName}")) {
Storage::disk('local')->delete("img/products/{$recordSet->$productImageName}");
}
$file_moved = $productImage->move(public_path('img/products'), $productImageName);
$data->image = "{$productImageName}";
}
$products->save([
'name' => $request->name,
'category_id' => $request->category_id,
'description' => $request->description,
'price_neto' => $request->price_neto,
'iva' => $request->iva,
'price_total' => $request->price_total,
'image' => $productImageName,
]);
return response()->json([
'error' => false,
'products' => $products,
]);
}
Product.js
$("#btn-edit").click(function() {
var formData = new FormData($("#frmEditProduct")[0]);
formData.append('_method', 'put');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/product/' + $("#frmEditProduct input[name=product_id]").val(),
data: formData,
dataType: 'json',
success: function(data) {
$('#frmEditProduct').trigger("reset");
$("#frmEditProduct .close").click();
window.location.reload();
},
error: function(data) {
var errors = $.parseJSON(data.responseText);
$('#edit-product-errors').html('');
$.each(errors.messages, function(key, value) {
$('#edit-product-errors').append('<li>' + value + '</li>');
});
$("#edit-error-bag").show();
}
});
});
I have the following Ajax call on click(), The record deletes from the database table, But the ajax error section code executes, Not the success section. Also i do get an error of 405,
But the records gets delete, Following is the code.
$(".DeleteUser").click(function(){
var id = $(this).data("id");
var token = $(this).data("token");
$.ajax(
{
url: "users/"+id,
type: 'DELETE',
dataType: "text",
data: {
"id": id,
"_method": 'DELETE',
"_token": token,
},
success: function ()
{
console.log("it Work");
},
error: function() {
alert('fail');
}
});
console.log("It failed");
});
Server Side Code :
public function destroy($id) {
$user = $this->find($id);
$user->delete();
$notification = array(
'message' => 'User has been Deleted !',
'alert-type' => 'success',
);
return redirect()->route('users.index');
}
You have used 'type: "DELETE" '. Instead of that you should USE 'type:"post"' . You can also use 'get'
you are not ending your response.But redirecting to some other page.
Skip that redirection and end the request-response cycle.
public function destroy($id) {
$user = $this->find($id);
$user->delete();
$notification = array(
'message' => 'User has been Deleted !',
'alert-type' => 'success',
);
//return redirect()->route('users.index'); //skip it
header('Content-Type: application/json');
echo json_encode($notification);
}
I have the following Ajax request:
// JavaScript
function myFunc(pid) {
$.ajax({
type : "GET",
url : "testback.php",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
// PHP
require_once ("dbconnect.php");
if (isset ( $_GET ['q'] )) {
if ($_GET ['q'] == "testrequest") {
$pid = $_GET ['pid'];
$query = "SELECT * FROM `tab1` WHERE `pid` = " . $pid;
$json = array ();
if ($result = $link->query ( $query )) {
while ( $row = $result->fetch_assoc () ) {
array_push ( $json, $row );
}
}
header ( "Content-type: application/json; charset=utf-8" );
die ( json_encode ( $json ) );
exit ();
}
die ();
}
It sends a request to my MySQL database and returns the expected output.
However, I now want to switch to POST, rather than GET.
When I just swap GET with POST:
// JavaScript
function myFunc(pid) {
$.ajax({
type : "POST", // POST
url : "testback.php",
contentType : "application/json; charset=utf-8",
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
}
// PHP
require_once ("dbconnect.php");
if (isset ( $_POST ['q'] )) { // POST
if ($_POST ['q'] == "testrequest") { // POST
$pid = $_POST ['pid']; // POST
$query = "SELECT * FROM `tab1` WHERE `pid` = " . $pid;
$json = array ();
if ($result = $link->query ( $query )) {
while ( $row = $result->fetch_assoc () ) {
array_push ( $json, $row );
}
}
header ( "Content-type: application/json; charset=utf-8" );
die ( json_encode ( $json ) );
exit ();
}
die ();
}
I get the following error in the console:
parsererror SyntaxError: Unexpected end of JSON input
The request payload is still q=testrequest&pid=1.
What else do I need to change, in order to switch from GET to POST?
In your Ajax function you need to omit the content type as it is already defined in the Ajax Call. Delete the line "contentType : "application/json; charset=utf-8" shown below:
$.ajax({
type : "GET", // Or POST
url : "testback.php",
contentType : "application/json; charset=utf-8", // REMOVE THIS LINE!!
dataType : "json",
data : {
q : "testrequest",
pid : pid
},
success : function(data) {
console.log(data)
},
error : function(jqXHR, status, error) {
console.log(status, error);
}
});
It should work just fine after that!
Cheers!
The $.ajax works but i advise to use $.get or $.post instead.
Be carrefull about your url when you use $.get, browsers have caracter limits (around 2000 caracters).
if (urlGet.length < 2000) {
// GET less than 2000 caractères use $.GET
$.get(urlGet, function () {
}).done(function (data) {
//OK do stuff with data returned
}).fail(function () {
//err
});
} else {
//Use $.POST params : { name: "John", age: "25" }
$.post(urlPost, { name: "John", age: "25" }, function () {
}).done(function () {
//ok
}).fail(function () {
//fail
});
}
You can create a function with this code and then have a simple call of your WebServices.
Here is the jQuery doucmentation :
$.GET https://api.jquery.com/jquery.get/
$.POST https://api.jquery.com/jquery.post/
Hope this help ;)
i cannot get the json from php on sever
the javascript code is:
$.ajax({
type: "POST",
url: "doingSQL.php",
data: label,
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
the job of doingSQL.php is selecting bookName from SQL database and convert the data to json. it look like this:
/* the server connecting code is omitted */
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$label = $_POST["label"];
}
$sql = "SELECT * FROM book WHERE ower = '". $label."'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$Arr = array("id" => $row["book_id"],
"bookName" => $row["bookName"]);
$bookDetail[] = array( "book".$i => $Arr);
}}
}
mysqli_close($conn);
$json = array("mybook" => $bookDetail);
echo json_encode($json);// return json
but the result i got in the html console is "[ ]" or array[0].
the json is valid json format, it is look like:
{
"mybook":[
{
"book0":{
"id":"0",
"bookName":"bookA"
}
},
{
"book1":{
"id":"1",
"bookName":"bookB"
}
}
]
}
however, if the code is outside the SQL connection in php. the json returning will success.
it is look like:
/* the server connecting code is omitted */
mysqli_close($conn);
// if outside the SQL connection
$ArrA = array("id" => "0", "bookName" => "bookA");
$ArrB = array("id" => "1", "bookName" => "bookB");
$bookDetail[] = array( "book0" => $ArrA);
$bookDetail[] = array( "book0" => $ArrB);
$json = array("mybook" => $bookDetail);
echo json_encode($json);// return json success
any idea?
Just pass your ajax data as :
data: {label:label}
The data property of the ajax settings can be type of PlainObject or String or Array. For more reference see this http://api.jquery.com/jquery.ajax.
So your javascript code would be like this :
$.ajax({
type: "POST",
url: "doingSQL.php",
data: {label: label},
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
You need to pass the label value in a variable. Now since on the PHP page you are using $_POST['label'], so pass the variable like this :
data: {label: label},
So your complete ajax code would look like :
$.ajax({
type: "POST",
url: "doingSQL.php",
data: {label: label}, // changed here
success: function(result) {
$("#p").html("All my book: <br>"+ result);
console.log(result);
},
dataType: "json",
error: function(xhr){
console.log("error");
}
});
I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}